<template>
  <div class="orders-page">
    <div class="page-header">
      <h2>订单管理</h2>
      <div>
        <el-button type="primary" @click="showCreateDialog">创建订单</el-button>
        <el-button type="primary" @click="exportOrders">导出订单</el-button>
      </div>
    </div>

    <!-- 订单统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ orderStats.total }}</div>
          <div class="stat-label">总订单数</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ orderStats.pending }}</div>
          <div class="stat-label">待支付</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ orderStats.paid }}</div>
          <div class="stat-label">已支付</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ orderStats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-number">{{ orderStats.canceled }}</div>
          <div class="stat-label">已取消</div>
        </div>
      </el-card>
      <el-card class="stat-card total-amount">
        <div class="stat-content">
          <div class="stat-number">¥{{ orderStats.totalAmount.toFixed(2) }}</div>
          <div class="stat-label">总消费金额</div>
        </div>
      </el-card>
    </div>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已取消" value="canceled" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <!-- 管理员可见的用户ID筛选 -->
        <el-form-item v-if="isAdmin" label="用户ID">
          <el-input 
            v-model="filterForm.userId" 
            placeholder="请输入用户ID"
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        border
      >
        <el-table-column prop="orderId" label="订单号" width="120" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="totalPrice" label="总价" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120">
          <template #default="scope">
            {{ getPaymentMethodText(scope.row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentTime" label="支付时间" width="180">
          <template #default="scope">
            {{ scope.row.paymentTime ? formatDate(scope.row.paymentTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="viewOrderDetail(scope.row)"
                >
                  查看
                </el-button>
                <el-button
                  v-if="scope.row.status === 'pending'"
                  link
                  type="success"
                  size="small"
                  @click="confirmPayment(scope.row)"
                >
                  确认支付
                </el-button>
                <el-button
                  v-if="scope.row.status === 'pending'"
                  link
                  type="danger"
                  size="small"
                  @click="cancelOrder(scope.row)"
                >
                  取消订单
                </el-button>
                <el-button
                  v-if="scope.row.status === 'pending'"
                  link
                  type="danger"
                  size="small"
                  @click="deleteOrder(scope.row)"
                >
                  删除订单
                </el-button>
              </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建订单对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建订单"
      width="600px"
    >
      <el-form ref="createFormRef" :model="createForm" label-width="80px">
        <el-form-item label="支付方式">
          <el-select v-model="createForm.paymentMethod" placeholder="请选择支付方式">
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
            <el-option label="银行卡" value="bankcard" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="门票信息">
          <div v-if="createForm.tickets.length === 0" class="empty-tickets">
            <p>暂无门票信息，请添加门票</p>
          </div>
          
          <div v-else class="ticket-list">
            <div v-for="(ticket, index) in createForm.tickets" :key="index" class="ticket-item">
              <span>门票ID: {{ ticket.ticketId }}, 数量: {{ ticket.quantity }}</span>
              <el-button type="danger" size="small" @click="removeTicket(index)">移除</el-button>
            </div>
          </div>
          
          <div class="add-ticket-form">
            <el-input v-model="ticketForm.ticketId" placeholder="门票ID" style="width: 150px; margin-right: 10px;" />
            <el-input-number v-model="ticketForm.quantity" :min="1" :step="1" style="width: 120px; margin-right: 10px;" />
            <el-button type="primary" @click="addTicket">添加</el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createOrder">创建</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="600px"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.orderId }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrder.status)">
              {{ getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ getPaymentMethodText(currentOrder.paymentMethod) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentOrder.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ currentOrder.paymentTime ? formatDate(currentOrder.paymentTime) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="总价格" :span="2">¥{{ currentOrder.totalPrice.toFixed(2) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 订单商品列表 -->
        <div class="order-items" v-if="currentOrder.orderTickets">
          <h4>订单商品</h4>
          <el-table :data="currentOrder.orderTickets" border style="width: 100%">
            <el-table-column prop="ticketId" label="门票ID" width="100" />
            <el-table-column label="门票信息" min-width="200">
              <template #default="scope">
                {{ getTicketInfoText(scope.row.ticket) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="unitPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.unitPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="100">
              <template #default="scope">
                ¥{{ (scope.row.unitPrice * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/services/api'
import { useAuthStore } from '@/stores/auth'

// 响应式数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const orderList = ref([])
const detailDialogVisible = ref(false)
const createDialogVisible = ref(false)
const currentOrder = ref(null)
// 订单统计数据，初始化为0
const orderStats = ref({
  total: 0,
  pending: 0,
  paid: 0,
  completed: 0,
  canceled: 0,
  totalAmount: 0
})

// 检查是否为管理员用户
const isAdmin = computed(() => {
  // 使用Pinia auth store获取用户角色信息
  const authStore = useAuthStore()
  return authStore.isAdmin
})

// 过滤表单
const filterForm = reactive({
  status: '',
  dateRange: [],
  userId: '' // 仅管理员可见的用户ID筛选字段
})

// 创建订单表单
const createForm = reactive({
  paymentMethod: '',
  tickets: []
})

const ticketForm = reactive({
  ticketId: '',
  quantity: 1
})

const createFormRef = ref(null)

// 获取订单列表
const getOrders = async () => {
  loading.value = true
  try {
    // 构建通用查询参数
    const commonParams = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加日期范围筛选
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      commonParams.startDate = filterForm.dateRange[0]
      commonParams.endDate = filterForm.dateRange[1]
    }
    
    let response
    
    // 如果有状态筛选
    if (filterForm.status) {
      console.log('按状态查询订单，状态：', filterForm.status)
      
      // 管理员用户需要特殊处理，因为后端/status/:status接口默认限制userId
      if (isAdmin.value) {
        // 管理员使用/user接口并添加状态筛选，这样可以获取所有用户的特定状态订单
        commonParams.status = filterForm.status
        response = await api.get('/order/user', { params: commonParams })
      } else {
        // 普通用户使用/status/:status接口
        response = await api.get(`/order/status/${filterForm.status}`, { params: commonParams })
      }
      
      // 验证响应数据格式
      if (response.data && response.data.code === 200 && response.data.data) {
        // 优先使用带分页的列表结构
        if (response.data.data.list) {
          orderList.value = response.data.data.list || []
          total.value = response.data.data.total || 0
        } else {
          // 兼容旧的数据格式
          orderList.value = Array.isArray(response.data.data) ? response.data.data : []
          total.value = orderList.value.length
        }
      } else {
        console.warn('API返回数据格式不符合预期', response.data)
        ElMessage.warning('获取订单数据格式异常')
        orderList.value = []
        total.value = 0
      }
    } else {
      // 无状态筛选，根据管理员权限和用户ID筛选决定API路径
      if (isAdmin.value && filterForm.userId) {
        // 管理员且有用户ID筛选，使用用户订单API
        commonParams.filterUserId = filterForm.userId
        response = await api.get('/order/user', { params: commonParams })
      } else {
        // 其他情况使用获取所有订单API
        response = await api.get('/order/all/order')
      }
      
      // 验证响应数据格式
      if (response.data && response.data.code === 200 && response.data.data) {
        // 优先使用带分页的列表结构
        if (response.data.data.list) {
          orderList.value = response.data.data.list || []
          total.value = response.data.data.total || 0
        } else {
          // 兼容旧的数据格式
          orderList.value = Array.isArray(response.data.data) ? response.data.data : []
          total.value = orderList.value.length
        }
      } else {
        console.warn('API返回数据格式不符合预期', response.data)
        ElMessage.warning('获取订单数据格式异常')
        orderList.value = []
        total.value = 0
      }
    }
    

    
  } catch (error) {
    console.error('获取订单失败：', error)
    
    // 重置订单列表和总数
    orderList.value = []
    total.value = 0
    
    // 分类错误提示
    if (error.response?.status === 401) {
      ElMessage.error('认证失败，请重新登录')
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法访问订单数据')
    } else {
      ElMessage.error('获取订单失败：' + 
        (error.response?.data?.message || 
         error.response?.statusText || 
         error.message || 
         '未知错误'))
    }
    

  } finally {
    loading.value = false
  }
}

// 处理订单查询
const handleFilter = () => {
  // 日期范围验证
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const startDate = new Date(filterForm.dateRange[0])
    const endDate = new Date(filterForm.dateRange[1])
    
    // 检查日期有效性
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      ElMessage.error('请选择有效的日期范围')
      return
    }
    
    // 检查开始日期是否晚于结束日期
    if (startDate > endDate) {
      ElMessage.error('开始日期不能晚于结束日期')
      return
    }
    
    // 检查日期范围是否超过365天
    const diffTime = Math.abs(endDate - startDate)
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    if (diffDays > 365) {
      ElMessage.error('日期范围不能超过365天')
      return
    }
  }
  
  // 重置页码并查询
  currentPage.value = 1
  getOrders()
}

// 重置过滤条件
const resetFilter = () => {
  filterForm.status = ''
  filterForm.dateRange = []
  filterForm.userId = '' // 重置用户ID筛选
  currentPage.value = 1
  getOrders()
}

// 查看订单详情
const viewOrderDetail = async (order) => {
  try {
    const response = await api.get(`/order/${order.orderId}`)
    if (response.data && response.data.code === 200 && response.data.data) {
      currentOrder.value = response.data.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

// 显示创建订单对话框
const showCreateDialog = () => {
  createForm.paymentMethod = ''
  createForm.tickets = []
  ticketForm.ticketId = ''
  ticketForm.quantity = 1
  createDialogVisible.value = true
}

// 添加门票
const addTicket = () => {
  if (!ticketForm.ticketId) {
    ElMessage.error('请输入门票ID')
    return
  }
  
  createForm.tickets.push({
    ticketId: ticketForm.ticketId,
    quantity: ticketForm.quantity
  })
  
  ticketForm.ticketId = ''
  ticketForm.quantity = 1
}

// 移除门票
const removeTicket = (index) => {
  createForm.tickets.splice(index, 1)
}

// 创建订单
const createOrder = async () => {
  if (!createForm.paymentMethod) {
    ElMessage.error('请选择支付方式')
    return
  }
  
  if (createForm.tickets.length === 0) {
    ElMessage.error('请至少添加一张门票')
    return
  }
  
  try {
    const response = await api.post('/order/create', {
      paymentMethod: createForm.paymentMethod,
      tickets: createForm.tickets
    })
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('订单创建成功')
      createDialogVisible.value = false
      getOrders()
      refreshStats()
    }
  } catch (error) {
    ElMessage.error('创建订单失败：' + (error.response?.data?.message || error.message))
  }
}

// 获取订单统计
const getOrderStats = async () => {
  try {
    console.log('正在请求订单统计数据...')
    // 确保API路径正确，直接使用后端定义的/stats路径
    const response = await api.get('/order/stats')
    
    console.log('订单统计API响应:', response)
    
    // 简化数据处理逻辑，直接使用后端返回的数据格式
    if (response.data && response.data.code === 200 && response.data.data) {
      orderStats.value = response.data.data
      console.log('更新后的订单统计数据:', orderStats.value)
    } else {
      console.warn('API返回数据格式不符合预期', response.data)
      
      // 显示模拟数据
      if (showMockDataWhenEmpty.value) {
        orderStats.value = {
          total: 10,
          pending: 3,
          paid: 5,
          completed: 2,
          canceled: 0,
          totalAmount: 1250.50
        }
        console.log('使用模拟数据:', orderStats.value)
      }
    }
  } catch (error) {
    console.error('获取订单统计失败：', error)
    console.error('错误状态码:', error.response?.status)
    console.error('错误详情:', error.response?.data || error.message)
    
    // 处理401认证错误
    if (error.response?.status === 401) {
      ElMessage.error('认证失败，请重新登录')
    } else {
      // 显示其他错误消息
      ElMessage.error('获取订单统计失败：' + 
        (error.response?.data?.message || 
         error.response?.statusText || 
         error.message || 
         '未知错误'))
    }
    
    // 在发生错误时设置模拟数据，避免页面空白
    if (showMockDataWhenEmpty.value) {
      orderStats.value = {
        total: 10,
        pending: 3,
        paid: 5,
        completed: 2,
        canceled: 0,
        totalAmount: 1250.50
      }
      console.log('错误时使用模拟数据:', orderStats.value)
    }
  }
}

// 辅助函数：获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待支付',
    paid: '已支付',
    completed: '已完成',
    canceled: '已取消'
  }
  return statusMap[status] || status
}

// 辅助函数：获取订单状态标签类型
const getOrderStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    paid: 'primary',
    completed: 'success',
    canceled: 'danger'
  }
  return typeMap[status] || 'default'
}

// 辅助函数：获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    alipay: '支付宝',
    wechat: '微信支付',
    bankcard: '银行卡'
  }
  return methodMap[method] || method
}

// 辅助函数：格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return dateString
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 辅助函数：获取门票信息文本
const getTicketInfoText = (ticket) => {
  if (!ticket) return '暂无信息'
  return ticket.name || `门票#${ticket.id}`
}

// 确认支付
const confirmPayment = async (order) => {
  try {
    const response = await api.put(`/order/update/${order.orderId}`, {
      status: 'paid'
    })
    if (response.data && response.data.code === 200) {
      ElMessage.success('订单已确认支付')
      getOrders()
      refreshStats()
    }
  } catch (error) {
    ElMessage.error('确认支付失败')
  }
}

// 取消订单
const cancelOrder = async (order) => {
  try {
    const response = await api.put(`/order/update/${order.orderId}`, {
      status: 'canceled'
    })
    if (response.data && response.data.code === 200) {
      ElMessage.success('订单已取消')
      getOrders()
      refreshStats()
    }
  } catch (error) {
    ElMessage.error('取消订单失败')
  }
}

// 删除订单
const deleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm('确定要删除此订单吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.delete(`/order/delete/${order.orderId}`)
    if (response.data && response.data.code === 200) {
      ElMessage.success('订单已删除')
      getOrders()
      refreshStats()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除订单失败')
    }
  }
}

// 刷新统计数据
const refreshStats = () => {
  getOrderStats()
}

// 导出订单
const exportOrders = () => {
  ElMessage.success('订单导出功能待实现')
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getOrders()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  getOrders()
}

// 初始加载
onMounted(() => {
  getOrders()
  getOrderStats()
})
</script>

<style scoped>
.orders-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 600;
}

/* 统计卡片样式 */
.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 150px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-card.total-amount .stat-number {
  color: #e6a23c;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail {
  .order-items {
    margin-top: 20px;
    
    h4 {
      margin-bottom: 10px;
    }
  }
}

/* 创建订单对话框样式 */
.empty-tickets {
  padding: 20px 0;
  text-align: center;
  color: #909399;
}

.ticket-list {
  margin-bottom: 15px;
}

.ticket-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 8px;
}

.add-ticket-form {
  margin-top: 10px;
  padding: 10px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}
</style>